package org.lex.net.http;

import java.io.IOException;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.log4j.Logger;
import org.lex.net.http.HttpSender.Builder;
import org.lex.net.http.HttpSender.Method;

/**
 * @author Liu Er Xiao
 * @version 1.0, 2009-2-20
 */
public class HttpRequest {
	private static final int RETRY_COUNT = 3;
	private static final int READ_TIMEOUT = 60000;// 60 seconds

	private Logger log = Logger.getLogger(HttpRequest.class);

	/**
	 * Use HTTP POST method to send a String <code>requestBody</code> as request
	 * body to specified server<code>url</code>, and return server response.<br>
	 * If remote server failed to response, <code>null</code> will be returned
	 * 
	 * @param url
	 *            Server address
	 * @param request
	 *            Request body
	 * @return server response, or <code>null</code> if server failed to
	 *         response
	 */
	public String post(String url, String requestBody) {
		Builder builder = HttpSender.builder();
		builder.setMethod(Method.POST);
		builder.setUrl(url);
		builder.setRetryTimes(RETRY_COUNT);
		builder.setTimeout(READ_TIMEOUT);

		SendResult result = null;
		try {
			builder.setRequestBody(requestBody);
			result = builder.build().send();
			int statusCode = result.getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				return result.getResponse();
			} else {
				log.error("HTTP response statusCode=" + statusCode + " error");
				return null;
			}
		} catch (HttpException e) {
			log.error("Connect server " + url + " failed", e);
		} catch (IOException e) {
			log.error("Read response failed", e);
		} finally {
			if (null != result) {
				result.releaseConnection();
			}
		}
		return null;
	}
}
